package com.android.nearshop.app.adapter.listadapter;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.shop.ShopDetailActivity;
import com.android.nearshop.app.widget.PullToRefreshListView;
import com.android.nearshop.app.widget.LoadableView.IdisplayNetErrAndRefreshView;
import com.android.nearshop.app.widget.PullToRefreshListView.OnRefreshListener;
import com.android.nearshop.io.protocol.ProtocolManager;
import com.android.nearshop.io.protocol.in.ShopDisCountListAction;
import com.android.nearshop.io.protocol.in.SoapAction.ActionListener;
import com.android.nearshop.io.protocol.out.DisShop;
import com.android.nearshop.io.protocol.out.DisShopList;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.ImageLoader;
import com.android.nearshop.util.ImageLoader.Imager;

/**
 * @File: MemDateAdapter.java
 * @Description:会员日列表适配器
 * @Author: denglixia
 * @Date: 2012-8-21
 * @Copyright : copyrights reserved by personal 2012-2022
 */
public class MemDateAdapter extends LoadableListAdapter<DisShop> 
implements OnScrollListener,DataLoaderHandler<DisShop>
{
    private ShopDisCountListAction mShopDisCountListAction;
	private OnClickListener mOnItemClick;
	private boolean isAreaChaned = false;
	private IdisplayNetErrAndRefreshView mNetView;
	
	public MemDateAdapter(final Context context,ListView listview) 
	{
	    // 使用公共的载入适配器[zhaohua]
		super(context,listview,null);
		setDataLoaderHandler(this);
		
		mOnItemClick = new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(v.getTag() instanceof ViewHolder){
	    			ViewHolder vh = (ViewHolder) v.getTag();
	    			if(vh.mShopId > 0){
	    				Intent intent = new Intent();
	    				intent.setClass(context.getApplicationContext(), ShopDetailActivity.class);
	    				intent.putExtra(Constant.TAG_DETAIL_SHOPID, vh.mShopId);
	    				intent.putExtra(Constant.TAG_DISCOUNT, vh.mDiscount.getText());
	    				
	    				context.startActivity(intent);
	    			}
				}
			}
	    };
	    
	    if(listview instanceof PullToRefreshListView)
        {
            PullToRefreshListView pullListview = (PullToRefreshListView)listview;
            pullListview.setOnRefreshListener(new OnRefreshListener()
            {
                @Override
                public void onRefresh()
                {
                    reload();
                    getNext(MemDateAdapter.this);
                }
            });
        }
	}
	
	/** 设置网络异常窗口监听者*/
    public void setIdisplayNetErrAndRefreshView(IdisplayNetErrAndRefreshView view)
    {
        this.mNetView = view;
    }
    
	 /**
     * 这个由外部控制
     * @param action
     * @param loadingView 包含 activity_findshop布局的可以实例话这个对象
     */
    public void setAction(ShopDisCountListAction action)
    {
    	mShopDisCountListAction = action;
        mShopDisCountListAction.setActionListener(mActionListener);
    }

	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		// modify by huangyue 切屏后概率会出现点击无法进入商家详细
		ViewHolder viewHolder = null;
		
//		int pos = position % 5;
//		if(mListItmeViewCache.size() < (pos+1))
//		{
//		    mListItmeViewCache.add(null);
//		}
		if(convertView == null )
        {
            convertView = inflater.inflate(R.layout.list_item_memdate, null);
            convertView.setOnClickListener(mOnItemClick);
//            mListItmeViewCache.set(pos, viewHolder);
        }
       
		if(convertView.getTag() != null && convertView.getTag() instanceof ViewHolder){
			viewHolder = (ViewHolder) convertView.getTag();
		} else {
			viewHolder = new ViewHolder();
			convertView.setTag(viewHolder);
		}
		
        viewHolder.mShopIcon = (ImageView) convertView
        		.findViewById(R.id.shopicon);
        viewHolder.mShopName = (TextView) convertView
        		.findViewById(R.id.shop_name);
        /*viewHolder.mRatingBar_Recommend = (RatingBar) convertView
        		.findViewById(R.id.recommend);*/
        viewHolder.mShopCategory = (TextView) convertView
        		.findViewById(R.id.shop_category);
        viewHolder.mDiscountDetail = (TextView) convertView
        		.findViewById(R.id.discount_detail);
        viewHolder.mAddress = (TextView) convertView
        		.findViewById(R.id.shop_address);
        viewHolder.mDistance = (TextView) convertView
        		.findViewById(R.id.distance);
        viewHolder.mDiscount = (TextView) convertView
        		.findViewById(R.id.discount);
        viewHolder.convertView = convertView;
        Resources res = mContext.getResources();
        DisShop disShop = (DisShop) getItem(position);
        viewHolder.mShopName.setText(disShop.shopName);
        //viewHolder.mRatingBar_Recommend.setRating((float)disShop.recommend);
        String category = res.getString(R.string.category_format,
        		disShop.catalogyName);
        viewHolder.mShopCategory.setText(category);
        viewHolder.mDiscountDetail.setText(disShop.discountdetail);
        viewHolder.mAddress.setText(disShop.shopAdd);
        
        setDistance(viewHolder, disShop.posDistance);
        setDiscount(viewHolder,res,disShop);
        
        ImageLoader.getInstance().DisplayImage(new Imager(disShop.imageUrl, viewHolder.mShopIcon, 97,R.drawable.default_detail_pic));
        viewHolder.mShopId = disShop.shopId;
        
        //end
		return convertView;
	}
	
    private void setDistance(ViewHolder viewHolder, double distance)
    {
//        double distance = Math.round(shop.posDistance * 100) / 100.0;
        if (distance > 1000)
        {
            viewHolder.mDistance.setText(Math.round(distance / 10)
                    / 100.0 + "km");
        } else
        {
            viewHolder.mDistance.setText(Math.round(distance * 100)
                    / 100.0 + "m");
        }
    }
	
	private void setDiscount(ViewHolder viewHolder, Resources res, DisShop shop)
    {
        if (shop.discount == null)
        {
            viewHolder.mDiscount.setVisibility(View.INVISIBLE);
            return;
        } else
        {
            viewHolder.mDiscount.setVisibility(View.VISIBLE);
        }
        String discount = null;
        try
        {
            Float.parseFloat(shop.discount);
            discount = res.getString(R.string.discount, shop.discount);
        } catch (Exception e)
        {
            discount = shop.discount;
        }

        viewHolder.mDiscount.setText(discount);
    }

	class ViewHolder
    {
	    View convertView;
	    int mShopId;
		ImageView mShopIcon;
        TextView mShopName;
        RatingBar mRatingBar_Recommend;
        TextView mShopCategory;
        TextView mDiscountDetail;
        TextView mAddress;
        TextView mDistance;
        public TextView mDiscount;

        ViewHolder()
        {}
    }
	
	private ActionListener<DisShopList> mActionListener = 
	    new ActionListener<DisShopList>()
    {
        @Override
        public void onSucceed(DisShopList result)
        {
            // 考虑没有分页，直接重新载入
            reload();
            if(result != null)
            {
                onLoaded(result.list);
            }else
            {
                onLoaded(null);
            }
        }
        @Override
        public void onError(int resultCode)
        {
            MemDateAdapter.super.onError();
        }
    };

    //////////////////////////////////////////////////////////////////////////////////////   
    @Override
    public int getMaxItems()
    {
        return 10;
    }

    @Override
    public void getNext(final DataLoadedCallback<DisShop> callback)
    {
        if(mNetView != null && !MyApplication.getContext().isNetWorkAvailable())
        {
            mNetView.showNoNetworkDialog();
        }else
        {
            showLoading();        
            ProtocolManager.getProtocolManager().submitAction(mShopDisCountListAction);
        }
    }

    @Override
    public boolean isLoading()
    {
        return mShopDisCountListAction.isLoading();
    }

    @Override
    public boolean haveNext()
    {
        // 由于这里没有分页，所以为false[zhaohua]
    	if(getCount() == 0)
    	{
    		return true;
    	}
        return false;
    }
    
    public void onReload()
    {
        if(isAreaChaned || getCount() == 0)
        {
            isAreaChaned = false;
            getNext(this);
        }
    }
    
    public void setAreaId(int areaId)
    {
        mShopDisCountListAction.setAreaId(areaId);
        isAreaChaned = true;
    }
}
